import { Text, View } from 'native-base';
import React, { useEffect, useState } from 'react';
import { CommonStyle } from '../../../../common/commonStyle.ts';
import { TouchableOpacity } from 'react-native';
import { Recording } from '../../../../component/RecordingModal.tsx';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../../redux/store.ts';
import { updateRecording } from '../../../../redux/reducers/app.ts';
import AudioRecorderClass from '../../../../utils/AudioRecorderClass.ts';
import Tools from '../../../../utils/Tools.ts';
import { useAsyncEffect } from 'ahooks';

interface IAdditionalFormProps {
  item: IGoodsAdditionalInfo;
  edit?: boolean;
  onChange: (value: string) => void;
}
export default function AdditionalFormRecord({ item, edit, onChange }: IAdditionalFormProps) {
  const recordingFile = useSelector((state: RootState) => state.recording);
  const dispatch = useDispatch<AppDispatch>();
  const [recorder] = useState(new AudioRecorderClass());
  const [play, setPlay] = useState<boolean>(false);

  useEffect(() => {
    dispatch(updateRecording(''));
  }, []);

  useAsyncEffect(async () => {
    if (recordingFile) onChange(await Tools.convertFileToBase64(recordingFile));
  }, [recordingFile]);

  // 播放录音文件
  const handlePlayRecorderFile = async () => {
    setPlay(true);
    await recorder.playRecording(
      recordingFile,
      (hasComplete) => {
        hasComplete && setPlay(false);
      },
      (progress) => {},
    );
  };

  return (
    <View flexDirection={'row'} alignItems={'center'} py={4} flex={1}>
      <View width={'25%'} flexDirection={'row'}>
        {item.requiredFlag && !edit && (
          <Text marginRight={1} color={CommonStyle.price}>
            *
          </Text>
        )}
        <Text marginRight={2} fontSize={12}>
          {item.attrName}
        </Text>
      </View>
      {!recordingFile && (
        <TouchableOpacity onLongPress={() => Recording.show('确 认')} style={{ flex: 1, borderRadius: 8, backgroundColor: CommonStyle.mainColor, paddingVertical: 6 }}>
          <Text color={'white'} textAlign={'center'}>
            长按录音
          </Text>
        </TouchableOpacity>
      )}
      {recordingFile && (
        <TouchableOpacity style={{ flex: 1, borderRadius: 8, backgroundColor: CommonStyle.mainColor, paddingVertical: 6 }} onPress={handlePlayRecorderFile}>
          <Text color={'white'} textAlign={'center'}>
            {!play ? '播放录音' : '播放中...'}
          </Text>
        </TouchableOpacity>
      )}
    </View>
  );
}
